import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from .models import Book, Category, Ads
from user.models import CustomUser
from operate.models import Collect
import random


# Create your views here.
def index(request):
    """
    新建路由函数
    :param request: 用于处理请求信息
    :return: 返回响应字符串
    """
    cs = Category.objects.all()
    adss = Ads.objects.all()
    print(request.user.is_authenticated)
    return render(request, "main/index.html", context={"cs": cs, "adss": adss})


def detail(request, num):
    # 使用get找到num对应id的书
    book = Book.objects.get(id=num)
    # render 函数是一个快捷函数，用于将请求（request）、一个模板（template）
    # 和可选的上下文（context）数据结合起来，生成一个 HttpResponse 对象
    return render(request, "main/detail.html", context={"book": book})


def about(request):
    return render(request, "main/about.html")


def recommend(request):
    return render(request, "main/recommend.html")


def load_data(request):
    books = Book.objects.all()
    books = list(books)
    datas = random.sample(books, k=4)
    datas = [{
        "id": data.id,
        "title": data.title,
    } for data in datas]
    return JsonResponse({
        "code": 0,
        "msg": "刷新成功",
        "data": datas,
    })
